package com.demo.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

@Repository
public class BaseDao<T> {

	/** 
     * 按属性查找唯一对象, 匹配方式为相等. 
     * 
     * @param propertyName 键
     * @param value 值
     * @return 实体对象
     */
	@SuppressWarnings("unchecked")
	protected T findUniqueBy(final String propertyName,final Object value,Class clazz){
		Assert.hasText(propertyName, "propertyName");
		Criterion criterion = Restrictions.eq(propertyName, value);
		return (T)createCriteria(clazz, criterion).uniqueResult();
	}
	
	/** 
     * create List base on  Class & Criterion
     *  
     * @param clazz
     * @param criterions 
     * @return List
     */  
	@SuppressWarnings("unchecked")
	protected List<T> find(final String propertyName,final Object value,Class clazz){
		Assert.hasText(propertyName, "propertyName");
		Criterion criterion = Restrictions.eq(propertyName, value);
		return (List<T>)createCriteria(clazz, criterion).list();
	}
	
	/** 
     * 根据Criterion条件创建Criteria. 
     * 与find()函数可进行更加灵活的操作. 
     *  
     * @param criterions 数量可变的Criterion.
     * @return Criteria
     */  
	protected Criteria createCriteria(final Class clazz,final Criterion...criterions){
		Criteria criteria = getSession().createCriteria(clazz);
		for(Criterion c : criterions){
			criteria.add(c);
		}return criteria;
	}
	
	
	
	
	/**
     * 获得当前上下文Session
     * @return Session
     */
	protected Session getSession(){
		return this.sessionFactory.getCurrentSession();
	}
	
	private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }
    public SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}
